/**
 * 
 */
package cn.edu.bjtu.model.core;

import java.io.IOException;
import java.util.concurrent.Future;

import org.deeplearning4j.eval.Evaluation;
import org.deeplearning4j.nn.graph.ComputationGraph;
import org.deeplearning4j.util.ModelSerializer;
import org.nd4j.linalg.api.ndarray.INDArray;
import org.nd4j.linalg.dataset.api.iterator.DataSetIterator;
import org.textplantform.common.core.Deep4jModelType;
import org.textplantform.common.provider.NetworkModelService;

/**
 * @author alex
 *
 */
public class NoDetectUpateComputationGraphSlave extends Slave{
	
	ThreadLocal<ComputationGraph> threadModel = new ThreadLocal<ComputationGraph>(){
		public ComputationGraph get() {
			if(super.get() == null){
				try {
					return ModelSerializer.restoreComputationGraph(getStream());
				} catch (IOException e) {
					// TODO Auto-generated catch block
					super.set(null);
					return null;
				}
			}else{
				return super.get();
			}
		};
	};
	public NoDetectUpateComputationGraphSlave(NetworkModelService nms) {
		super(nms,false);
	}

	@Override
	public INDArray[] output(INDArray... input) throws Exception {
		ComputationGraph temp = threadModel.get();
		return temp == null?DumpSlave.ALLONE.output(input):temp.output(input);
	}

	@Override
	public Future<INDArray[]> outputAsync(INDArray... input) throws Exception {
		throw new RuntimeException(" Not Support Async in Spark Environment ");
	}

	@Override
	public Evaluation evaluate(DataSetIterator iterator) throws Exception {
		ComputationGraph temp = threadModel.get();
		return temp == null?DumpSlave.ALLONE.evaluate(iterator):temp.evaluate(iterator);
	}

	@Override
	public Future<Evaluation> evaluateAsync(DataSetIterator iterator) throws Exception {
		throw new RuntimeException(" Not Support Async in Spark Environment ");
	}

	@Override
	public Deep4jModelType getActualType() {
		return Deep4jModelType.Local;
	}

	@Override
	public void load() throws Exception {
		System.out.println(" ===Lazy=== ");
	}

	@Override
	Object get() {
		return threadModel.get();
	}

}
